package com.xl.basic.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xl.basic.entity.Result;
import com.xl.basic.entity.ResultEnums;
import com.xl.basic.entity.param.AddRoleUserParam;
import com.xl.basic.entity.param.DelRoleUserParam;
import com.xl.basic.entity.UserInfo;
import com.xl.basic.service.RoleUserService;
import com.xl.dao.domain.XlRoleUser;
import com.xl.dao.mapper.XlRoleUserMapper;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author 钟勇
 * Create in 2023/8/30 10:31
 */
@Service
@RequiredArgsConstructor
public class RoleUserServiceImpl implements RoleUserService {

    private final XlRoleUserMapper roleUserMapper;

    @Override
    public Result<Object> addRoleUser(@NonNull AddRoleUserParam param, UserInfo operator) {
        if (roleUserMapper.selectCount(new LambdaUpdateWrapper<XlRoleUser>()
                .eq(XlRoleUser::getState, 1)
                .eq(XlRoleUser::getUserId, param.getUserId())
                .eq(XlRoleUser::getRoleId, param.getRoleId())
        ) > 0) {
            return ResultEnums.Success.getResult();
        }

        if (roleUserMapper.insert(new XlRoleUser()
                .setRoleId(param.getRoleId())
                .setUserId(param.getUserId())
                .setState(1)
                .setAddTime(LocalDateTime.now())
                .setAddUser(operator == null ? null : operator.getUserId())
        ) <= 0) {
            return ResultEnums.Exception.getResult("用户写入失败");
        }

        return ResultEnums.Success.getResult();
    }

    @Override
    public Result<Object> delRoleUser(@NonNull DelRoleUserParam param, UserInfo operator) {
        LambdaUpdateWrapper<XlRoleUser> wrapper = new LambdaUpdateWrapper<XlRoleUser>()
                .eq(XlRoleUser::getState, 1)
                .eq(XlRoleUser::getUserId, param.getUserId())
                .eq(XlRoleUser::getRoleId, param.getRoleId());
        if (roleUserMapper.selectCount(wrapper) <= 0) {
            return ResultEnums.Success.getResult();
        }

        if (roleUserMapper.update(new XlRoleUser()
                        .setState(0)
                        .setUpdTime(LocalDateTime.now())
                        .setUpdUser(operator == null ? null : operator.getUserId()),
                wrapper
        ) <= 0) {
            return ResultEnums.Exception.getResult("用户写入失败");
        }

        return ResultEnums.Success.getResult();
    }

}
